package com.example.spring.controller;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class SendController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping("/send")
    public String send() {
        String content = "Date：" + new Date();
        amqpTemplate.convertAndSend("queue-test1", content);
        return content;
    }

    /**
     * 发送者发送一个消息被多个接收者接收，注意这里的消息只能被消费一次
     *
     * @return
     */
    @RequestMapping("/multisend")
    public String multiSend() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            long time = System.nanoTime();
            amqpTemplate.convertAndSend("queue-test1", "第" + i + "次发送的时间：" + time);
            sb.append(time + "<br>");
        }
        return sb.toString();
    }

    /**
     * 多对多发送消息，不同的接收者接收不同发送者发送的消息，消息也可以是实体对象
     *
     * @return
     */
    @RequestMapping("/multiMultiSend")
    public String multiMultiSend() {
        StringBuilder times = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            long time = System.nanoTime();
            amqpTemplate.convertAndSend("queue-test1", "第" + i + "次发送的时间：" + time);
            amqpTemplate.convertAndSend("queue-test2", "第" + i + "次发送的时间：" + time);
            times.append(time + "<br>");
        }
        return times.toString();
    }

    /**
     * Topic Exchange是RabbitMQ中最灵活的一种方式，它能够根据routing_key自由的绑定不同的队列
     *
     * @return
     */
    @RequestMapping("/topicSend1")
    public String topicSend1() {
        String content = "my topic1";
        System.out.println("发送者说：" + content);
        amqpTemplate.convertAndSend("topicExchange", "topic.message", content);
        return content;
    }

    @RequestMapping("/topicSend2")
    public String topicSend2() {
        String content = "my topic2";
        System.out.println("发送者说：" + content);
        amqpTemplate.convertAndSend("topicExchange", "topic.messages", content);
        return content;
    }

    /**
     * Fanout Exchange就是我们熟悉的广播模式，给Fanout交换机发送消息，绑定了这个交换机的所有队列都收到这个消息。
     */
    @RequestMapping("/fanoutSend/{content}")
    public String fanoutSendAll(@PathVariable("content") String content) {
        System.out.println("发送者说：" + content);
        amqpTemplate.convertAndSend("fanoutExchange", "", content);
        return content;
    }

    @RequestMapping("/directSend")
    public String directSend() {
        String content = "hello world";
        System.out.println("发送者说：" + content);
        amqpTemplate.convertAndSend("directExchange", "direct.msg2", content);
        return content;
    }

}